package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class CharServer2 {

	public static void main(String[] args) {
		//设置服务器的监听端口，启动服务器监听
		
		int  port = 8888;
		
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		    try {
		    	//1.启动服务器监听
				serverSocket = new ServerSocket(port);
				System.out.println("服务器启动成功，请使用客户端进行连接！");
				//2.等待客户端进行连接
				 socket  = serverSocket.accept();
				 System.out.println("客户端连接成功");
				 //3.客户端连接后，打开输入流(准备从客户端读取数据输入)
				 inputStream =  socket.getInputStream();
				 outputStream =  socket.getOutputStream();
				 //4.读取客户端发生过来的数据
				 boolean chatting = true;
				 while(chatting) {
					 //发送数据到客户端
					 byte[] buffer = new byte[512];
					//等待客户端发生数据，并接受  -有阻塞作用
					 int len = inputStream.read(buffer);
					 //5.对数据进行处理
					 String  string = new String(buffer, 0, len);
					
					 System.out.println(string);
					 //发送数据到客户端 
					 outputStream.write(("parrot ：" + string).getBytes());
					 
					 //网络通信需要有一方发起结束通信请求，另一方需要接收退出请求，并进行正常退出
					 if("quit".equalsIgnoreCase(string.trim())) {
						 chatting =false;
					 }
					 
				 }
				
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				//6.关闭输入流
				if(outputStream!=null) {
					try {
						outputStream.close();
					} catch (IOException e) {
					}
				}
				if(inputStream!=null) {
					try {
						inputStream.close();
					} catch (IOException e) {
					}
				}
				if(socket!=null) {
					try {
						socket.close();
					} catch (IOException e) {
					}
				}
				if(serverSocket!=null) {
					try {
						serverSocket.close();
					} catch (IOException e) {
					}
				}
			}
		
	
		
		
		
	}


}
